from PyQt5.QtCore import Qt, QSize
from PyQt5.QtWidgets import (
    QWidget, QMainWindow, QListWidget, QHBoxLayout, QListWidgetItem)

from src.forward.base.bean import tables
from src.forward.base.bean import forward


@forward(name='main')
class Home(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setGeometry(100,100,700,500)
        center=QWidget()
        self.layout=QHBoxLayout()
        center.setLayout(self.layout)
        self.setCentralWidget(center)
        # 左侧目录
        self.left_widget=QListWidget()
        self.left_widget.setStyleSheet("""
            QListWidget { background-color: #E3D3D3; }
            QListWidget::item:selected { background-color: #FF0000; color: white; }  # 例如：选中时背景为红色，文字为白色
        """)
        self.left_widget.setFixedWidth(100)
        # 添加项目，并设置每个项目的文本对齐方式
        items = [k for k in tables.keys() if k != 'main']
        for item_text in items:
            item = QListWidgetItem(item_text)
            item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)  # 设置文本居中
            self.left_widget.addItem(item)
        self.layout.addWidget(self.left_widget)
        # 设置项目间距
        self.left_widget.setStyleSheet("""
                                           QListWidget::item {
                                               margin: 10px;  /* 设置项目的外边距 */
                                           }
                                       """)

        self.left_widget.currentRowChanged.connect(self.change)
        self.right_widget=QWidget()

        self.layout.addWidget(self.right_widget)

    def change(self,index):

        # 更新标签的文本以反映当前选中的项
        item_text = self.left_widget.item(index).text() if index >= 0 else ''
        new_widget=tables[item_text]()
        new_widget.fill_data()
        if self.right_widget:
            self.layout.replaceWidget(self.right_widget,new_widget)
            self.right_widget.setParent(None)  # 从父窗口中移除
        self.right_widget=new_widget
        # 遍历布局中的所有小部件

    def clear_layout(self, layout):
        # 移除布局中的所有控件
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()  # 删除控件